public class num993 {
    int x;
    int xDeth;
    TreeNode xFather = null;
    int y;
    int yDeth;
    TreeNode yFather = null;
    public boolean isCousins(TreeNode root, int x, int y) {
        this.x = x;
        this.y = y;
        dfs(root,0,null);
        return xDeth == yDeth && xFather != yFather;
    }

    private void dfs(TreeNode root,int deth,TreeNode parent) {
        if(root == null) {
            return;
        }
        if(root.val == x || root.val == x) {
            xFather = root;
            xDeth = deth + 1;
            xFather = parent;
        } else if(root.val == y || root.val == y) {
            yFather = root;
            yDeth = deth + 1;
            yFather = parent;
        }
        dfs(root.left,deth + 1,root);
        dfs(root.right,deth + 1,root);
    }
}
